import sys
import ldap
import re

l = ldap.initialize('ldap://ldap.isu.edu')
base = 'o=isu.edu,o=isp'

def getbylastname(name):
	result  = l.search_s(base,ldap.SCOPE_SUBTREE,'(sn=%s)' % name,['cn','mail'])
	if len(result) > 0: return result
	else: return None

	

def getbyfirstname(name):
	result = l.search_s(base,ldap.SCOPE_SUBTREE, '(givenName=%s)' % name,['cn','mail'])
	if len(result)>0: return result
	else: return None

# So, if I pass in the string 'John Q. Smith (123456)', then fragments will look
# like ['john', 'q', 'smith', '123456', '']. Then, for each of the 5 pieces in
# fragments you are going to do 2 LDAP searches, several of which could return
# large result sets. I think we can be more efficient than that. Let's try to do
# just one search per input, and make it specific enough that we return the
# smallest possible result set.
#
# Also, your algorithm isn't semantically correct. When I pass in an input
# string "Paul J Link" I get this result: [('Paul K Link', 'linkpaul@isu.edu'),
# ('Marta J Link', 'linkmart@isu.edu')] neither one of which matches the input.

def search(raw):
	# this could more directly be done: raw = raw.replace("'", "")
	filter = raw.split('\'')
	raw = ''.join(filter)
	fragments = re.split('\W+',raw)
	fragments = [x.lower() for x in fragments]
	catch_firstname  = []
	catch_lastname = []
	for pieces in fragments:
		try1 = getbyfirstname(pieces)
		if (try1):
			for temp in try1:
				# you could just write temp not in catch_firstname
				if ((temp in catch_firstname) == False): catch_firstname.append(temp)
		try2 = getbylastname(pieces)
		if (try2): 
			for temp in try2: 
				if ((temp in catch_lastname) == False): catch_lastname.append(temp)
	
	
	all_matches = catch_firstname + catch_lastname
	
	result = []
	for each_match in all_matches:
		cnt = 0
		name = each_match[1]['cn'][0]
		name_broken = name.split()
		for each_name_broken in name_broken:
			if (each_name_broken.lower() in fragments): cnt += 1
		if (cnt > 1):
			result.append((each_match[1]['cn'][0],each_match[1]['mail'][0]))
		if (len(fragments)==1):
			result.append((each_match[1]['cn'][0],each_match[1]['mail'][0]))
	result = list(set(result))	
	
	return result
			

if __name__=='__main__':
	search(sys.argv[1])


